package com.huluspace.datajdbc.service;

import com.huluspace.datajdbc.dao.UserDao;
import com.huluspace.datajdbc.dao.UserRoleDao;
import com.huluspace.datajdbc.model.User;
import com.huluspace.datajdbc.security.CustomUserDetails;
import com.huluspace.datajdbc.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class JwtAuthService {

  final private JwtUtil jwtUtil;
  final private UserDao userDao;
  final private UserRoleDao userRoleDao;
  public JwtAuthService(JwtUtil jwtUtil, UserDao userDao, UserRoleDao userRoleDao) {
    this.jwtUtil = jwtUtil;
    this.userDao = userDao;
    this.userRoleDao = userRoleDao;
  }

  // 基于JWT鉴权并封装用户详情
  public CustomUserDetails loadUserByToken(String token) {
    if (!jwtUtil.validateToken(token)) {
      throw new RuntimeException("Invalid token");
    }
    String username = jwtUtil.extractUserName(token);
    User user = userDao.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found"));
    List<GrantedAuthority> authorities = getAuthoritiesByUserName(username);
    return new CustomUserDetails(user.getId(), user.getUsername(), "", authorities);
  }

  // 获取用户权限
  private List<GrantedAuthority> getAuthoritiesByUserName(String username) {
    return userRoleDao.findRolesByUserName(username).stream()
        .map(role -> new SimpleGrantedAuthority(role.trim()))
        .collect(Collectors.toList());
  }
}
